package com.syl.practice.globalException2.handler;

import com.alibaba.fastjson.JSON;
import com.syl.practice.globalException2.anno.ResponseResult;
import com.syl.practice.globalException2.result.RespResult;
import com.syl.practice.globalexception.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@ControllerAdvice
public class MyAnnoHandler implements ResponseBodyAdvice<Object> {

    private final static String RESPONSE_RESULT_ANN = "RESPONSE_RESULT_ANN";

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attrs.getRequest();
        ResponseResult responseResultAnno = (ResponseResult) request.getAttribute(RESPONSE_RESULT_ANN);
        return responseResultAnno == null ? false : true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        log.info("统一处理返回体");
        // 异常
        if (o instanceof ApiException) {
            return new RespResult((ApiException) o);
        }

        // 成功
        RespResult result = new RespResult(o);
        if (o instanceof String) {
            return JSON.toJSONString(result);
        }
        return result;
    }
}
